package com.pengpeng.sheepfoldmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pengpeng.sheepfoldmall.product.entity.AttrEntity;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pengpeng.common.utils.PageUtils;
import com.pengpeng.common.utils.Query;

import com.pengpeng.sheepfoldmall.product.dao.ProductAttrValueDao;
import com.pengpeng.sheepfoldmall.product.entity.ProductAttrValueEntity;
import com.pengpeng.sheepfoldmall.product.service.ProductAttrValueService;
import org.springframework.transaction.annotation.Transactional;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存spu的规则参数（发布商品时）
     * @param productAttrValueEntities
     */
    @Override
    public void saveProductAttrValue(List<ProductAttrValueEntity> productAttrValueEntities) {
        this.saveBatch(productAttrValueEntities);
    }

    /**
     * 获取spu规格（spu管理点‘规格’按钮时跳转页面回显）
     * @param spuId
     * @return
     */
    @Override
    public List<ProductAttrValueEntity> listForSpu(Long spuId) {
        List<ProductAttrValueEntity> list = this.list(new LambdaQueryWrapper<ProductAttrValueEntity>()
                .eq(ProductAttrValueEntity::getSpuId, spuId));
        return list;
    }

    /**
     * 修改商品规格
     * @param spuId
     * @param list
     */
    @Transactional
    @Override
    public void updateSpuAttr(Long spuId, List<ProductAttrValueEntity> list) {
        //先批量删除对应spu的规格参数
        baseMapper.delete(new LambdaQueryWrapper<ProductAttrValueEntity>().eq(ProductAttrValueEntity::getSpuId,spuId));
        //再将传进来的修改数据添加上spuId并批量保存
        List<ProductAttrValueEntity> collect = list.stream().map(item -> {
            item.setSpuId(spuId);
            return item;
        }).collect(Collectors.toList());
        this.saveBatch(collect);
    }

    /**
     * 查询当前spu所有可展示的规格属性
     * @param spuId
     */
    @Override
    public List<ProductAttrValueEntity> qryEnableSearchAttrBySpuId(Long spuId) {
        return baseMapper.qryEnableSearchAttrBySpuId(spuId);
    }
}